package com.nhjf.admin.interceptor;


import com.nhjf.admin.common.util.SysProperties;
import com.nhjf.admin.util.Jurisdiction;
import com.nhjf.common.Constants;
import com.nhjf.common.util.LogMessage;
import com.nhjf.common.util.StringUtil;
import com.nhjf.model.system.AdminSession;
import com.nhjf.model.system.Resource;
import com.nhjf.model.system.User;
import com.nhjf.pojo.qo.system.AdminSessionQo;
import com.nhjf.pojo.qo.system.ResourceQo;
import com.nhjf.pojo.qo.system.UserQo;
import com.nhjf.service.system.AdminSessionService;
import com.nhjf.service.system.ResourceService;
import com.nhjf.service.system.UserService;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 * @author 拦截器
 *
 */
/**
 * @类功能说明：
 * @类修改者：
 * @修改日期：
 * @修改说明：
 * @部门：技术部
 * @作者：龚一凡
 * @创建时间：2017年8月7日上午10:55:17
 * @版本：V1.0
 */
public class CommonInterceptor implements HandlerInterceptor {

	private Logger logger = Logger.getLogger(CommonInterceptor.class);
	private static UserService userService;
	private static AdminSessionService adminSessionService;
	private static ResourceService resourceService;

	public CommonInterceptor() {
	}

	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		String path = request.getServletPath();
		try {
			Session session = Jurisdiction.getSession();
			String url =  request.getServletPath();
			ServletContext sc = request.getSession().getServletContext();
		    XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
		    if(cxt != null && cxt.getBean("userService") != null && userService == null) {
		    	userService = (UserService) cxt.getBean("userService");
		    }
		    if(cxt != null && cxt.getBean("adminSessionService") != null && adminSessionService == null) {
		    	adminSessionService = (AdminSessionService) cxt.getBean("adminSessionService");
		    }	
		    if(cxt != null && cxt.getBean("resourceService") != null && resourceService == null) {
		    	resourceService = (ResourceService) cxt.getBean("resourceService");
		    }	
		    
			User user=(User)session.getAttribute(com.nhjf.common.Constants.USER_INFO);
			
			// 判断是否是接口请求地址，如果为接口请求地址直接不做验证
			if (url.indexOf("/login/check") >= 0) {
				return true;
			}else if(url.indexOf("/login//valid-code-image.jpg") >= 0){
				return true;
			}else if(url.indexOf("/monitorAction") >= 0){
				return true;
			}else if(url.indexOf("/user/modifyUserPwd") >= 0){ // 网页头部修改密码不需要设置资源
				return true;
			}else if(url.indexOf("/helpInfo/execute") >= 0){
				return true;
			}else if(url.indexOf("/notifyAction") >= 0) {
				return true;
			}else if(url.indexOf("/resource") >= 0) {
				return true;
			}else if(url.indexOf("/uedit") >= 0) {
				return true;
			}else if(url.indexOf("/adminAction") >= 0) {
				return true;
			}else{
				String[] noNeed = Constants.NONEEDURL;
				boolean noNeedtage = false;
				int leng = noNeed.length;
				for (int i = 0; i < leng; i++) {
					if (url.indexOf(noNeed[i]) >= 0) {
						noNeedtage = true;
						break;
					}
				}
				if (!noNeedtage) {
					if(user==null) {
						String loginToken="";
						Cookie[] cookies = request.getCookies();
					    for(Cookie cookie : cookies){
					        if(cookie.getName().equals("loginToken")){
					            loginToken = cookie.getValue();
			
					        }
					     } 
						if(StringUtils.isNotEmpty(loginToken)) {
							AdminSessionQo adminSessionQo=new AdminSessionQo();
							adminSessionQo.setToken(loginToken);
							AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
							if(adminSession!=null) {
								Date todayTime=new Date();
								if(todayTime.before(adminSession.getExpiryTime())) {
									if(((int)(adminSession.getExpiryTime().getTime()-todayTime.getTime())/(1000 * 60))<10) {
						                Calendar c = Calendar.getInstance();  
						                c.setTime(todayTime); 
						                c.add(Calendar.MINUTE,45 );
						                adminSession.setExpiryTime(c.getTime());
						                adminSessionService.update(adminSession);
									}
							    	UserQo qo=new UserQo();
							    	qo.setUserName(adminSession.getLoginName());
							    	qo.setSeachRole(true);
							    	User userOne=userService.queryUnique(qo);
							    	session.setAttribute(com.nhjf.common.Constants.USER_INFO,userOne);
							    	ResourceQo resourceQoall=new ResourceQo();
							    	resourceQoall.setUserId(userOne.getId());
							    	List<Resource>	reslistall=resourceService.queryList(resourceQoall);
							    	session.setAttribute("resourceList",reslistall);
							    	ResourceQo resourceQo=new ResourceQo();
							    	resourceQo.setUserId(userOne.getId());
							    	resourceQo.setParentId(101055L);
							    	List<Resource>	reslist=resourceService.queryList(resourceQo);//
							    	for(Resource res:reslist) {
								    	ResourceQo rQo=new ResourceQo();
								    	rQo.setUserId(userOne.getId());
								    	rQo.setParentId(res.getId());
								    	List<Resource>	rlist=resourceService.queryList(rQo);//
								    	res.setResourceList(rlist);
							    	}
							    	session.setAttribute("reslist",reslist);
								}else {
									Cookie[] cookiess = request.getCookies();//获取cookie
									for (Cookie cookie: cookiess) {
								        if ("loginToken".equals(cookie.getName())) {
									        cookie.setMaxAge(0);
									        cookie.setPath("/");
									        response.addCookie(cookie);
								        }
									}
									response.sendRedirect(request
											.getContextPath() + "/login");
									return false;
								}
							}else {
								Cookie[] cookiess = request.getCookies();//获取cookie
								for (Cookie cookie: cookiess) {
							        if ("loginToken".equals(cookie.getName())) {
								        cookie.setMaxAge(0);
								        cookie.setPath("/");
								        response.addCookie(cookie);
							        }
								}
								response.sendRedirect(request
										.getContextPath() + "/login");
								return false;
							}
						}else {
							Cookie[] cookiess = request.getCookies();//获取cookie
							for (Cookie cookie: cookiess) {
						        if ("loginToken".equals(cookie.getName())) {
							        cookie.setMaxAge(0);
							        cookie.setPath("/");
							        response.addCookie(cookie);
						        }
							}
							response.sendRedirect(request
									.getContextPath() + "/login");
							return false;
						}
						

					}else {
						String loginToken="";
						Cookie[] cookies = request.getCookies();
					    for(Cookie cookie : cookies){
					        if(cookie.getName().equals("loginToken")){
					            loginToken = cookie.getValue();
			
					        }
					     } 
						if(StringUtils.isNotEmpty(loginToken)) {
							AdminSessionQo adminSessionQo=new AdminSessionQo();
							adminSessionQo.setToken(loginToken);
							AdminSession adminSession=adminSessionService.queryUnique(adminSessionQo);
							if(adminSession!=null) {
								if(adminSession.getLoginName().equals(user.getUserName())) {
									
								}else {
							       
									session.removeAttribute(com.nhjf.common.Constants.USER_INFO);
									session.removeAttribute("resourceList");
									Date todayTime=new Date();
									if(todayTime.before(adminSession.getExpiryTime())) {
										if(((int)(adminSession.getExpiryTime().getTime()-todayTime.getTime())/(1000 * 60))<10) {
							                Calendar c = Calendar.getInstance();  
							                c.setTime(todayTime); 
							                c.add(Calendar.MINUTE,45 );
							                adminSession.setExpiryTime(c.getTime());
							                adminSessionService.update(adminSession);
										}
								    	UserQo qo=new UserQo();
								    	qo.setUserName(adminSession.getLoginName());
								    	qo.setSeachRole(true);
								    	User userOne=userService.queryUnique(qo);
								    	session.setAttribute(com.nhjf.common.Constants.USER_INFO,userOne);
								    	ResourceQo resourceQoall=new ResourceQo();
								    	resourceQoall.setUserId(userOne.getId());
								    	List<Resource>	reslistall=resourceService.queryList(resourceQoall);
								    	session.setAttribute("resourceList",reslistall);
								    	ResourceQo resourceQo=new ResourceQo();
								    	resourceQo.setUserId(userOne.getId());
								    	resourceQo.setParentId(0L);
								    	List<Resource>	reslist=resourceService.queryList(resourceQo);//
								    	for(Resource res:reslist) {
									    	ResourceQo rQo=new ResourceQo();
									    	rQo.setUserId(userOne.getId());
									    	rQo.setParentId(res.getId());
									    	List<Resource>	rlist=resourceService.queryList(rQo);//
									    	res.setResourceList(rlist);
								    	}
								    	session.setAttribute("reslist",reslist);
									}else {
										Cookie[] cookiess = request.getCookies();//获取cookie
										for (Cookie cookie: cookiess) {
									        if ("loginToken".equals(cookie.getName())) {
										        cookie.setMaxAge(0);
										        cookie.setPath("/");
										        response.addCookie(cookie);
									        }
										}
										response.sendRedirect(request
												.getContextPath() + "/login");
										return false;
									}
								}
								
							}else {
								Cookie[] cookiess = request.getCookies();//获取cookie
								for (Cookie cookie: cookiess) {
							        if ("loginToken".equals(cookie.getName())) {
								        cookie.setMaxAge(0);
								        cookie.setPath("/");
								        response.addCookie(cookie);
							        }
								}
								response.sendRedirect(request
										.getContextPath() + "/login");
								return false;
							}
						}else {
							Cookie[] cookiess = request.getCookies();//获取cookie
							for (Cookie cookie: cookiess) {
						        if ("loginToken".equals(cookie.getName())) {
							        cookie.setMaxAge(0);
							        cookie.setPath("/");
							        response.addCookie(cookie);
						        }
							}
							response.sendRedirect(request
									.getContextPath() + "/login");
							return false;
						}
					} 
					if (url.indexOf("/home") >= 0) {
						return true;
					}
					List<Resource> plist = (List<Resource>)session.getAttribute("resourceList");

					boolean tage = false;
					int length = plist.size();
					for (int i = 0; i < length; i++) {
						if (StringUtil.isNotNull(plist.get(i).getUrl())) {
							String url1 = plist.get(i).getUrl();
							if (url.indexOf(url1) >= 0) {
								tage = true;
								break;
							}
						}
					}

					if (tage) {
						return true;
					} else {
						if (((HttpServletRequest) request)
								.getHeader("x-requested-with") == null) {
							response.setCharacterEncoding("UTF-8");
							response.getWriter().write("您无此权限！请联系管理员。");
							response.sendRedirect(request
									.getContextPath() + "/no.jsp");
						} else {
							response.setCharacterEncoding("UTF-8");
							response.getWriter().write("您无此权限！请联系管理员。");
							response.sendRedirect(request
									.getContextPath() + "/no.jsp");
						}
						return false;
					}
				} else {
					return true;
				}
			}
		} catch (Exception e) {
			LogMessage.logwrite(this.getClass(), e.getMessage());
			response.sendRedirect(request
					.getContextPath() + "/login");
			return false;
		}

		
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
//		 log.info("==============执行顺序: 2、postHandle================");
		//获取图片地址
		String imagePath = SysProperties.getInstance().get("imagePath");
		request.setAttribute("imagePath", imagePath);
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
//		 log.info("==============执行顺序: 3、afterCompletion================");
	}

}
